package name.fuhan.biaoqing_fh;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import name.fuhan.biaoqing_fh.BiaoQing_in.BiaoQing;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Parcelable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.widget.TextView;

public class BiaoQing_Show extends TextView {

	public BiaoQing_Show(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public BiaoQing_Show(Context context) {
		super(context);
	}

	public void setBiaoQingString(String biaoQingString) {
		setMovementMethod(LinkMovementMethod.getInstance());
		int atList = biaoQingString.indexOf("AT*");
		String json = biaoQingString.substring(atList + 3);
		List<Map<String, String>> list = new Gson().fromJson(json,
				new TypeToken<List<Map<String, String>>>() {
				}.getType());
		biaoQingString = biaoQingString.substring(0, atList);

		SpannableString text = new SpannableString(biaoQingString);

		int atStart = 0;// 下标
		int atEnd = 0;
		int count = 0;// 计数
		while ((atStart = biaoQingString.indexOf("@", atEnd)) != -1) {
			Map<String, String> map = list.get(count++);
			Intent intent = new Intent(getContext(),
					BiaoQing_in.Config.showUserActivity);
			Set<String> keySet = map.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				String value = map.get(key);
				intent.putExtra(key, value);
			}
			text.setSpan(new BiaoQing_in.MyURLSpan(intent, getContext(),
					BiaoQing_in.Config.showUserActivity), atStart, atEnd = biaoQingString
					.indexOf(" ", atStart), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		}
		String path = BiaoQing_in.Config.path;
		int jieshu = 0;
		while (true) {
			int kaishi = biaoQingString.indexOf("&[", jieshu);
			if (kaishi == -1) {
				break;
			}
			jieshu = biaoQingString.indexOf("]", kaishi);
			String name = biaoQingString.substring(kaishi + 2, jieshu);

			try {
				InputStream open = getContext().getResources().getAssets()
						.open(path + "/" + name);
				Bitmap bitmap = BiaoQing_in.decodeSampledBitmapFromResource(
						open, getLineHeight(), getLineHeight());
				open.close();
				bitmap = Bitmap.createScaledBitmap(bitmap, getLineHeight(),
						getLineHeight(), true);
				text.setSpan(new ImageSpan(getContext(), bitmap), kaishi,
						jieshu + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		setText(text);
	}

}
